package com.mywork.mvpkodeingithub.app

import android.util.Log
import com.mywork.mvpkodeingithub.BuildConfig
import com.mywork.mvpkodeingithub.base.BaseApplication
import com.mywork.mvpkodeingithub.di.appKodeinModule
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.LogStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance

class KodeinApp : BaseApplication(), KodeinAware {
    override val kodein: Kodein = Kodein.lazy {
        bind() from instance(filesDir)//Logger
        import(appKodeinModule)
    }

    override fun onCreate() {
        super.onCreate()
        val formatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(true)
            //.tag("Yunmu-Log")
            .logStrategy(LogCatStrategy())
            .build()

        Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) {
            override fun isLoggable(priority: Int, tag: String?): Boolean {
                return BuildConfig.DEBUG
            }
        })
    }

    //由于AS3.0打印相同TAG时，会自动隐藏前面TAG，造成排版问题，把TAG增加乱数可解决排版问题
    inner class LogCatStrategy : LogStrategy {

        private var last: Int = 0

        override fun log(priority: Int, tag: String?, message: String) {
            Log.println(priority, randomKey() + tag!!, message)
        }

        private fun randomKey(): String {
            var random = (10 * Math.random()).toInt()
            if (random == last) {
                random = (random + 1) % 10
            }
            last = random
            return random.toString()
        }
    }
}